package br.ufpe.cin.wormbox.protocolo;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class RPFTServer {

	private DatagramSocket UDPS;
	int port;

	public RPFTServer(int port) throws SocketException {
		this.UDPS = new DatagramSocket(port);
		this.port = port;
	}
	
	public RPFTServer() throws SocketException {
		this.UDPS = new DatagramSocket();
		this.port = this.UDPS.getLocalPort();
	}

	public RPFTSocket aceitarConexao() {
		DatagramPacket UDPSYN = new DatagramPacket(
				new byte[RPFTPacket.SpecialPacketLength],
				RPFTPacket.SpecialPacketLength);
		RPFTPacket SYN;
		RPFTSocket sock = null;

		try {
			do {
				this.UDPS.receive(UDPSYN);
				SYN = new RPFTPacket(UDPSYN.getData());
			} while (!SYN.isSYN());
			System.out.println("Recebi o SYN!!");
			
			sock = new RPFTSocket(UDPSYN.getAddress(), UDPSYN.getPort());
			
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(0);
		}

		return sock;
	}
	
	public int getPort() {
		return this.port;
	}
}
